#include "StdAfx.h"
#include "DepthFirstRouter.h"
#include "Character.h"

Character::Character(void)
{
	_router = new DepthFirstRouter();
	speed = 0.02f;

	bMoving = false;
}

Character::~Character(void)
{
	delete _router;
}

void Character::findRoute(iPos targetPos, std::vector<std::vector<char> > map)
{
	route.clear();

	route = _router->route(map, pos, targetPos);
	if (route.size()>0)
	{
		target = targetPos;
	}
	else
	{
		target.x = pos.x;
		target.y = pos.y;
	}
}

void Character::moveOneStep()
{
	int i;
	static int iSegPre=0;
	static int iSegNext = 1;
	static bool bAlign=false;

	if (bAlign)
	{
		if (DIST(route[iSegPre+1], pos)<=speed*1.5)
		{
			pos.x = route[iSegPre+1].x;
			pos.y = route[iSegPre+1].y;

			bAlign = false;

			iSegPre = iSegNext;

			
			
		}else
		{
			if (pos.x<route[iSegPre+1].x)
			{
				pos.x += speed;
			}
			else
				pos.x -= speed;

			if (pos.y<route[iSegPre+1].y)
			{
				pos.y += speed;
			}
			else
				pos.y -= speed;

			
		}

		if (bAlign)
		{
			return;
		}
		
	}

	if (DIST(target, pos)<=0.01f)
	{
		// if very close to the target, set to the target
		pos.x = target.x;
		pos.y = target.y;

		iSegPre = 0;
		iSegNext = 1;

		bMoving = false;
	}else
	{
		bMoving = true;

		// judge which segment it in
		int iSeg = 0;
		int x,y;
		for (i=0; i<route.size(); i++)
		{
			x = ROUND(pos.x);
			y = ROUND(pos.y);
			if (route[i].x == x && route[i].y == y)
			{
				iSeg = i;
				break;
			}
		}
		if (iSeg<route.size()-1)
		{
			if (iSeg>0)
			{
				if ((DIST(route[iSeg+1], pos) < DIST(route[iSeg-1], pos))||(abs(DIST(route[iSeg+1], pos)-DIST(route[iSeg-1], pos))<VERYSMALL))
				{
				}
				/*else
					iSeg--;*/
			}			
		}
		else if (iSeg==route.size()-1)
		{
			iSeg--;
		}
		if (iSeg!=iSegPre)
		{
			// if want to switch to another segment, go to the pre-seg point first				
			iSegNext = iSeg;
			bAlign = true;
		}
		else
		{
			// move one step
			pos.x = pos.x + (route[iSeg+1].x - route[iSeg].x)*speed;
			pos.y = pos.y + (route[iSeg+1].y - route[iSeg].y)*speed;
		}		
	}
}